import { RouteAPI } from '@/api/request/route'
import router from '@/router'
import { RouteRecord } from '@/router/async.router'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import store from '..'

const layers = [{ name: 'basic', layer: () => import('@/layout/BasicLayout.vue') }]

function getLayer(layerName: string) {
  const obj = layers.find(item => item.name === layerName)
  if (!obj) {
    throw new Error(`layer ${layerName} not found`)
  }
  return obj.layer
}

const permissionStore = defineStore('permission', () => {
  const asyncRoutes = ref<RouteRecordRaw[]>([])

  function generatingRoute(routes: RouteRecord[]) {
    const res: RouteRecordRaw[] = []
    routes.forEach(v => {
      // @ts-ignore
      const route: RouteRecordRaw = {
        path: v.path,
        meta: v.meta,
        redirect: v.redirect,
      }
      // * 层存在，则设置层
      if (v.layer) {
        route.component = getLayer(v.layer)
        route.meta && (route.meta.disable = true)
      } else if (v.component) {
        // * 层不存在，但是组件存在，则设置组件
        route.component = () => import(`../../pages${v.component}`)
      }
      if (v.children) {
        route.children = generatingRoute(v.children)
      }

      res.push(route)
    })

    return res
  }

  async function loadRoutes() {
    const [err, data] = await RouteAPI.getRoutes()
    if (!err) {
      asyncRoutes.value = generatingRoute(data)
      asyncRoutes.value.forEach(router.addRoute)
    }
  }

  return { asyncRoutes, generatingRoute, loadRoutes }
})

export const usePermissionStore = () => permissionStore(store)
